var express = require('express');
var router = express.Router();
var Q = require('q');
var Manager = require('../modules/mongo');
var DBManager =new Manager();

/* GET users listing. */
router.get('/', function(req, res, next) {
  let req_data = req.query
  DBManager.find('users', {}, {}, result =>{
    if(result.success){
      res.send({success:true, code:0,message:'查询用户成功',data:result.result})
    }else{
      res.send({success:false,code:1,message:'查询失败',data:[]});
    }
  })
});

router.post('/registeredUser', function(req, res, next){
  let req_data = req.body
  let params =Object.assign({},req_data,{create_time:new Date(), update_time:new Date()})
  DBManager.findOne('users', {phone:req_data.phone}, result=>{
    if(result.success){
      res.send({success:true, code:0,message:'电话号码已存在'})
      return ;
    }
    DBManager.insert('users', params, result =>{
      if(result.success){
        res.send({success:true, code:0,message:'新增用户成功'})
      }else{
        res.send({success:false,code:1,message:'上传失败'});
      }
    })
  })
});

router.post('/updateUser',function(req, res, next){
  let req_data = req.body
  let update_time = new Date()
  let whereData = {_id: req_data._id}
  let params = {
    "userName" : req_data.userName,
    "password" : req_data.password,
    "age" : req_data.age,
    "phone" : req_data.phone,
    "address" : req_data.address,
    "competence": req_data.competence,
    "update_time": update_time
  }
  DBManager.update('users', whereData, {$set:params})
  .then(result => {
    if(result.success){
      res.send({success:true, code:0,message:'更新用户成功'})
    }
  }).catch(err => {
    res.send({success:false, code:1,message:'更新用户失败'})
  })

})

router.post('/deleteUers', function(req, res, next){
  let req_data = req.body
  let whereData = {_id: req_data._id}
  DBManager.delete('users', whereData).then(result => {
    if(result.success){
      res.send({success:true, code:0, message:'删除用户成功'})
    }
  }).catch(err => {
    res.send({success:false, code:1, message:'删除用户失败'})
  })
})

module.exports = router;
